const fs = require('fs');
const path = require('path');
const mysql = require('mysql2/promise');
require('dotenv').config();

const initDatabase = async () => {
  try {
    // 创建数据库连接
    const connection = await mysql.createConnection({
      host: process.env.DB_HOST,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD
    });

    // 删除现有数据库
    await connection.query(`DROP DATABASE IF EXISTS ${process.env.DB_NAME}`);
    
    // 创建数据库
    await connection.query(`CREATE DATABASE IF NOT EXISTS ${process.env.DB_NAME}`);
    await connection.query(`USE ${process.env.DB_NAME}`);

    // 读取并执行SQL文件
    const sqlFile = path.join(__dirname, 'init.sql');
    const sql = fs.readFileSync(sqlFile, 'utf8');
    
    // 分割SQL语句并执行
    const statements = sql.split(';').filter(statement => statement.trim());
    for (const statement of statements) {
      if (statement.trim()) {
        await connection.query(statement);
      }
    }

    console.log('数据库初始化成功');
    await connection.end();
  } catch (error) {
    console.error('初始化数据库时出错：', error);
    process.exit(1);
  }
};

// 如果直接运行此文件，则执行初始化
if (require.main === module) {
  initDatabase();
}

module.exports = initDatabase; 